package com.lou1052.redis.jedis.source;

import com.lou1052.core.serializer.Serializer;
import com.lou1052.redis.jedis.api.JedisApi;
import com.lou1052.redis.jedis.api.JedisApiSource;
import com.lou1052.redis.jedis.config.JedisConfig;
import com.lou1052.redis.jedis.util.SerSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.function.Function;

/**
 * Jedis 连接资源对象
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/10/14
 * Time: 22:29
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbsJedisSource<J extends JedisApi> implements JedisApiSource,InitializingBean,DisposableBean {
    //配置项
    protected final JedisConfig jedisConfig;

    //
    protected final Function<String, Serializer> serializerFunction;


    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public AbsJedisSource(JedisConfig jedisConfig,SerSelector serSelector) {
        this.jedisConfig = jedisConfig;
        //例如 key=“mykey:kryo” 取得name=kryo 用kryo序列化
        this.serializerFunction=(key)->{
            if(key.contains(":")) {
                return serSelector.select(key.substring(key.lastIndexOf(":") + 1, key.length()));
            }else{
                return serSelector.getDefaultSerializer();
            }
        };
    }

    /**
     * 取得jedis连接
     * @return
     */
    public abstract J getSource();

}
